<?php

namespace App\Listeners;

use App\Events\LoanRequestRetryEvent;
use App\Facades\SamLogFacade;
use App\Library\String\Strings;
use App\Models\RetryLoanRequestHistory;
use App\Models\UserLoanRequest;
use Carbon\Carbon;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\DB;
use Exception;
use Illuminate\Support\Facades\Log;

class LoanRequestRetryEventListener
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Description:处理授信重试
     * Author: Sam
     * DateTime: 2019-03-11 10:24
     * @param LoanRequestRetryEvent $event
     * @throws Exception
     */
    public function handle(LoanRequestRetryEvent $event)
    {
        $loan = $event->loan;
        $isLoanApply = $event->isLoanApply;
        $loan_requests_id = $loan->id;
        $pid = getmypid();
        SamLogFacade::debug("特殊处理数据：".json_encode($loan,JSON_UNESCAPED_UNICODE));
        /**
         * 生成新的流水号
         */
        $new_trans_id = Strings::createSerialNumber($loan->user_id);
        $old_trans_id = $loan->trans_id;
        $old_credit_id = $loan->credit_id;
        $history = [
            'loan_requests_id'=>$loan_requests_id,
            'old_trans_id'=>$old_trans_id,
            'old_credit_id'=>$old_credit_id,
        ];
        DB::beginTransaction();
        try{
            RetryLoanRequestHistory::create($history);
            $loan->trans_id = $new_trans_id;
            $loan->retry = UserLoanRequest::RETRY_YES;
            $loan->retry_date = Carbon::now()->addDay()->toDateString();
            if($isLoanApply == true){
                // 标记为重试授信成功之后需要自动放款
                $loan->auto_loan_apply = UserLoanRequest::AUTO_LOAN_APPLY_YES;
                Log::debug('放款超额，更改授信放款状态为99，刷新授信流水号,loanId:' . $loan_requests_id);
            }
            $loan->save();
            DB::commit();
            SamLogFacade::debug("进程【{$pid}】处理授信记录【{$loan->id}】更改为需要重试状态");
        }catch (Exception $e){
            SamLogFacade::debug("进程【{$pid}】处理授信重试失败：{$e->getMessage()}");
            DB::rollBack();
        }

    }
}
